package com.hangzhou.xyj.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.hangzhou.xyj.R;
import com.hangzhou.xyj.XYJApplication;
import com.hangzhou.xyj.event.CorrectRespEvent;
import com.hangzhou.xyj.manager.IntentManager;
import com.hangzhou.xyj.model.type.ECorrectType;
import com.hangzhou.xyj.model.type.EIntentTagType;
import com.hangzhou.xyj.net.handler.SavePublishHandler;
import com.hangzhou.xyj.net.http.HttpLoader;
import com.hangzhou.xyj.net.http.okhttp.OkHttpClientManager;
import com.hangzhou.xyj.net.request.SaveGroupReq;
import com.hangzhou.xyj.ui.activity.base.BaseActivity;
import com.hangzhou.xyj.ui.widget.CircleImageView;
import com.hangzhou.xyj.ui.widget.CommonTitleBarView;
import com.hangzhou.xyj.ui.widget.multiimageselector.MultiImageSelectorActivity;
import com.hangzhou.xyj.ui.widget.views.MyImageView;
import com.hangzhou.xyj.ui.widget.views.MyTextView;
import com.hangzhou.xyj.utils.StringUtil;
import com.hangzhou.xyj.utils.ToastUtil;
import com.hangzhou.xyj.utils.constants.API;
import com.hangzhou.xyj.utils.constants.DataKey;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.io.IOException;
import java.util.List;

import okhttp3.Request;

/**
 * Created by neo.duan on 2016/1/17.
 */
public class AddGroupActivity extends BaseActivity implements View.OnClickListener {
    RelativeLayout mRlGroupIcon;//圈子图标
    EditText mEtGroupName;//圈子名称
    MyTextView mMtvGroupType;//圈子类别
    EditText mEtGroupIntroduce;//圈子简介
    String mFilePath;//选择的图片的路径
    String mFileNetPath;//图片的网上路径
    MyImageView mIvTip;//提示性的图片
    CircleImageView mCivImg;//显示的图片
    LinearLayout mLlChooseType;//圈子类别条

    private String mGroupName;//圈子名称
    private String mGroupType;//圈子类别
    private String mGroupIntroduce;//圈子简介
    private int mGroupId;//圈子类别的ID

    @Override
    public void initTop() {
        enableTitle(true, "新建圈子");
        enableRightNav(true, "确定");
        setOnNavRightListener(new CommonTitleBarView.OnNavRightListener() {
            @Override
            public void onNavRight() {
                mGroupName = mEtGroupName.getText().toString().trim();
                mGroupIntroduce = mEtGroupIntroduce.getText().toString().trim();
                if (StringUtil.isEmpty(mFilePath)) {
                    ToastUtil.show("请选择圈子头像");
                    return;
                }
                if (StringUtil.isEmpty(mGroupName)) {
                    ToastUtil.show("圈子名称不能为空");
                    return;
                }
                if (StringUtil.isEmpty(mGroupType)) {
                    ToastUtil.show("全选择圈子类别");
                    return;
                }
                if (StringUtil.isEmpty(mGroupIntroduce)) {
                    ToastUtil.show("请输入圈子简介");
                    return;
                }
                uploadFile(mFilePath);
            }
        });
    }

    @Override
    public void initLayouts() {
        setContentView(R.layout.activity_add_group);
    }

    @Override
    public void initViews() {
        mRlGroupIcon = findView(R.id.rl_content);
        mEtGroupName = findView(R.id.et_group_name);
        mMtvGroupType = findView(R.id.mtv_group_type);
        mEtGroupIntroduce = findView(R.id.et_group_introduce);
        mIvTip = findView(R.id.miv_add_icon);
        mCivImg = findView(R.id.civ_id_card);
        mLlChooseType = findView(R.id.ll_choose_type);
    }

    @Override
    public void initDatas() {
        registerEventBus();
    }

    @Override
    public void initListeners() {
        mRlGroupIcon.setOnClickListener(this);
        mLlChooseType.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.rl_content:
                intent = new Intent(mContext, MultiImageSelectorActivity.class);
                // 是否显示调用相机拍照
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
                // 最大图片选择数量
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 1);
                // 设置模式 (支持 单选/MultiImageSelectorActivity.MODE_SINGLE 或者 多选/MultiImageSelectorActivity.MODE_MULTI)
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_SINGLE);
                IntentManager.getInstance().goImageSelectorActivity(AddGroupActivity.this, intent, 1);
                break;
            case R.id.ll_choose_type://选择圈子类别
                intent = new Intent(mContext, DramaCategoryListActivity.class);
                intent.putExtra(DataKey.INTENT_TAG, EIntentTagType.TAG_ADD_GROUP.getValue());
                intent.putExtra(DataKey.TITLE, "选择剧种");
                IntentManager.getInstance().goActivity(mContext, intent);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {
            // 获取返回的图片列表
            List<String> path = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
            mFilePath = path.get(0);
            mIvTip.setVisibility(View.GONE);
            mRlGroupIcon.setBackgroundColor(Color.parseColor("#FFFFFF"));
            ImageLoader.getInstance().displayImage("file:///" + mFilePath, mCivImg);
            mCivImg.setVisibility(View.VISIBLE);
        }
    }


    /**
     * 单个文件上传
     *
     * @param
     * @return 返回上传到服务器以后，文件在服务器上的地址
     * @author yaohuix
     * @date 2016/3/18 13:38
     */
    public void uploadFile(String fileName) {
        try {
            OkHttpClientManager.getInstance().postAsyn(API.FILE_UPLOAD, new OkHttpClientManager.ResultCallback<String>() {
                @Override
                public void onError(Request request, Exception e) {
                    ToastUtil.show("上传出错!，请重试！");
                }

                @Override
                public void onResponse(String response) {
                    JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                    boolean isSuccess = "success".equals(jsonObject.get("msg").getAsString()) ? true : false;
                    if (isSuccess) {
                        mFileNetPath = jsonObject.get("data").getAsString();
                        SaveGroupReq saveGroupReq = new SaveGroupReq(mMyUserId, XYJApplication.getCity(),
                                mGroupName, mGroupIntroduce, mGroupId, mGroupType, mFileNetPath);
                        HttpLoader.getInstance().sendRequest(new SavePublishHandler(saveGroupReq, new MyHttpResponseListener() {
                            @Override
                            public void onSuccess(Object model) {
                                super.onSuccess(model);
                                ToastUtil.show("新建圈子成功");
                                closeActivity();//关闭窗口
                            }
                        }, 0));
                    }
                }
            }, new File(fileName), "file");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }
    }

    /**
     * 选择圈子类别 事件订阅
     *
     * @param
     * @return
     * @author yaohuix
     * @date 2016/4/22 10:08
     */
    @Subscribe
    public void onEventMainThread(CorrectRespEvent event) {
        switch (ECorrectType.valueOf(event.getTag())) {
            case CHOOSE:
                mGroupType = event.getValue();
                mGroupId = Integer.valueOf(event.getValue2());
                mMtvGroupType.setText(mGroupType);
                break;
        }
    }

}
